const { ethers } = require('ethers');
require('dotenv').config();

/**
 * IPFS访问测试脚本
 * 用于诊断NFT图片不显示的问题
 */

// 你的IPFS信息
const IPFS_INFO = {
    // metadata文件hash
    metadataHash: "Qmd8wqnZoF1B1MFMJ3dZZr51e6wZKtjxsRTvVTAAWcuEjf",

    // 图片文件hash
    imageHash: "QmeFanMMX7wQyw8H9At2W3gmS1atEuNDGTcb5ftikU553V",

    // 图片文件名
    imageFile: "myNFT1.jpeg"
};

// 合约配置
const CONFIG = {
    rpcUrl: process.env.SEPOLIA_RPC_URL,
    privateKey: process.env.PRIVATE_KEY,
    contractAddress: "YOUR_CONTRACT_ADDRESS_HERE"
};

// 合约ABI
const CONTRACT_ABI = [
    "function tokenURI(uint256 tokenId) public view returns (string)",
    "function setTokenURI(uint256 tokenId, string memory _tokenURI) public",
    "function totalSupply() public view returns (uint256)"
];

class IPFSAccessTester {
    constructor() {
        this.provider = null;
        this.wallet = null;
        this.contract = null;
    }

    async initialize() {
        console.log("🚀 初始化IPFS访问测试器...");

        if (CONFIG.contractAddress === "YOUR_CONTRACT_ADDRESS_HERE") {
            console.log("⚠️  请先设置合约地址");
            return false;
        }

        this.provider = new ethers.providers.JsonRpcProvider(CONFIG.rpcUrl);
        this.wallet = new ethers.Wallet(CONFIG.privateKey, this.provider);
        this.contract = new ethers.Contract(CONFIG.contractAddress, CONTRACT_ABI, this.wallet);

        console.log("✅ 初始化完成");
        return true;
    }

    /**
     * 测试IPFS链接访问
     */
    async testIPFSAccess() {
        console.log("\n🌐 测试IPFS链接访问");
        console.log("=" * 40);

        const testLinks = [
            {
                name: "Metadata文件",
                hash: IPFS_INFO.metadataHash,
                urls: [
                    `https://ipfs.io/ipfs/${IPFS_INFO.metadataHash}`,
                    `https://gateway.pinata.cloud/ipfs/${IPFS_INFO.metadataHash}`,
                    `https://cloudflare-ipfs.com/ipfs/${IPFS_INFO.metadataHash}`
                ]
            },
            {
                name: "图片文件",
                hash: IPFS_INFO.imageHash,
                urls: [
                    `https://ipfs.io/ipfs/${IPFS_INFO.imageHash}`,
                    `https://gateway.pinata.cloud/ipfs/${IPFS_INFO.imageHash}`,
                    `https://cloudflare-ipfs.com/ipfs/${IPFS_INFO.imageHash}`
                ]
            },
            {
                name: "图片文件（带文件名）",
                hash: `${IPFS_INFO.imageHash}/${IPFS_INFO.imageFile}`,
                urls: [
                    `https://ipfs.io/ipfs/${IPFS_INFO.imageHash}/${IPFS_INFO.imageFile}`,
                    `https://gateway.pinata.cloud/ipfs/${IPFS_INFO.imageHash}/${IPFS_INFO.imageFile}`,
                    `https://cloudflare-ipfs.com/ipfs/${IPFS_INFO.imageHash}/${IPFS_INFO.imageFile}`
                ]
            }
        ];

        for (const test of testLinks) {
            console.log(`\n📁 ${test.name}:`);
            console.log(`   Hash: ${test.hash}`);
            console.log(`   IPFS URI: ipfs://${test.hash}`);

            for (const url of test.urls) {
                console.log(`   HTTP访问: ${url}`);
            }

            console.log(`   💡 请在浏览器中测试这些链接`);
        }
    }

    /**
     * 检查合约中的tokenURI
     */
    async checkContractTokenURI() {
        console.log("\n🔍 检查合约中的tokenURI");
        console.log("=" * 40);

        try {
            const totalSupply = await this.contract.totalSupply();
            console.log(`📊 总供应量: ${totalSupply}`);

            if (totalSupply.toNumber() === 0) {
                console.log("ℹ️  还没有铸造任何NFT");
                return;
            }

            for (let i = 1; i <= totalSupply; i++) {
                try {
                    const tokenURI = await this.contract.tokenURI(i);
                    console.log(`\n🆔 Token ${i}:`);
                    console.log(`   URI: ${tokenURI}`);

                    // 检查URI格式
                    if (tokenURI.startsWith('ipfs://')) {
                        const hash = tokenURI.replace('ipfs://', '');
                        console.log(`   Hash: ${hash}`);
                        console.log(`   HTTP访问: https://ipfs.io/ipfs/${hash}`);
                    }

                } catch (error) {
                    console.log(`   ❌ 查询失败: ${error.message}`);
                }
            }

        } catch (error) {
            console.error("❌ 检查失败:", error.message);
        }
    }

    /**
     * 分析metadata内容
     */
    analyzeMetadata() {
        console.log("\n📋 分析metadata内容");
        console.log("=" * 40);

        const metadata = {
            "name": "myNFT1",
            "description": "My first NFT artwork",
            "image": "ipfs://QmeFanMMX7wQyw8H9At2W3gmS1atEuNDGTcb5ftikU553V/myNFT1.jpeg",
            "attributes": [
                {
                    "trait_type": "Type",
                    "value": "Learning"
                },
                {
                    "trait_type": "Number",
                    "value": "1"
                }
            ]
        };

        console.log("📄 Metadata内容:");
        console.log(JSON.stringify(metadata, null, 2));

        console.log("\n🔍 分析结果:");
        console.log(`✅ name: ${metadata.name}`);
        console.log(`✅ description: ${metadata.description}`);
        console.log(`🔗 image: ${metadata.image}`);

        // 提取图片hash
        const imageHash = metadata.image.replace('ipfs://', '');
        console.log(`📁 图片hash: ${imageHash}`);
        console.log(`🌐 图片HTTP访问: https://ipfs.io/ipfs/${imageHash}`);

        console.log("\n💡 可能的问题:");
        console.log("1. 图片文件可能没有正确上传到IPFS");
        console.log("2. IPFS节点可能没有同步该文件");
        console.log("3. 图片文件路径可能不正确");
        console.log("4. 图片文件可能损坏或格式不支持");
    }

    /**
     * 提供解决方案
     */
    provideSolutions() {
        console.log("\n🔧 解决方案");
        console.log("=" * 40);

        console.log("1. 检查图片文件上传:");
        console.log("   - 确认图片文件已正确上传到IPFS");
        console.log("   - 检查图片文件是否损坏");
        console.log("   - 确认图片格式支持（JPEG, PNG, GIF等）");

        console.log("\n2. 测试IPFS访问:");
        console.log("   - 在浏览器中访问HTTP链接");
        console.log("   - 尝试不同的IPFS网关");
        console.log("   - 检查网络连接");

        console.log("\n3. 重新上传文件:");
        console.log("   - 重新上传图片文件到IPFS");
        console.log("   - 获得新的hash");
        console.log("   - 更新metadata文件");
        console.log("   - 重新上传metadata文件");

        console.log("\n4. 使用不同的IPFS服务:");
        console.log("   - 尝试Pinata");
        console.log("   - 尝试IPFS Desktop");
        console.log("   - 尝试其他IPFS服务");

        console.log("\n5. 检查metadata格式:");
        console.log("   - 确保JSON格式正确");
        console.log("   - 确保所有字段都存在");
        console.log("   - 确保image字段指向正确的文件");
    }

    /**
     * 运行所有测试
     */
    async runAllTests() {
        console.log("🎯 IPFS访问诊断");
        console.log("=" * 50);

        const initialized = await this.initialize();
        if (!initialized) {
            console.log("⚠️  跳过合约相关测试");
        }

        await this.testIPFSAccess();

        if (initialized) {
            await this.checkContractTokenURI();
        }

        this.analyzeMetadata();
        this.provideSolutions();

        console.log("\n📊 测试完成");
        console.log("💡 请根据上述信息诊断问题并采取相应措施");
    }
}

// 运行测试
async function main() {
    const tester = new IPFSAccessTester();
    await tester.runAllTests();
}

if (require.main === module) {
    main().catch(console.error);
}

module.exports = { IPFSAccessTester, IPFS_INFO };
